const Koa = require("koa");
const Router = require("@koa/router");
const static = require("koa-static");
const mount = require("koa-mount");
const compose = require("koa-compose");
const fs = require("fs");
const util = require("util");

const app = new Koa();
app.use(mount("/public", static(__dirname + "/public")));
const router = new Router();

app.use(async (ctx, next) => {
  try {
    const data = await util.promisify(fs.readFile)(
      __dirname + "/views/index.html",
      "utf8"
    );
    // 指定响应类型为html
    ctx.type = "html";
    ctx.body = data;
    next();
  } catch (err) {
    console.log(err);
  }
});

const one = (ctx, next) => {
  console.log(">> one");
  next();
  console.log("<< one");
};

const two = (ctx, next) => {
  console.log(">> two");
  next();
  console.log("<< two");
};

const three = (ctx, next) => {
  console.log(">> three");
  next();
  console.log("<< three");
};

// 中间件合并注册
app.use(compose([one, two, three]));
/* app.use(one);
app.use(two);
app.use(three); */

app.listen(3000, () => {
  console.log("Server is running at http://localhost:3000");
});
